import Vue from 'vue'
import VueRouter from 'vue-router'
import store from './store'
import { setAuth } from './http'
import NotFound from '@/components/pages/NotFound'
Vue.use(VueRouter)


const routes = [
    {
        path: '/',
        props:true,
    },
    {
        path: '/index',
        name: 'index',
        component: () => import(/* webpackChunkName: "index" */ '@/components/pages/Index'),
        // children: funcRoutes,
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/detail',
        name: 'detail',
        component: () => import(/* webpackChunkName: "detail" */ '@/components/pages/Detail'),
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/edit-record',
        name: 'edit-record',
        component: () => import(/* webpackChunkName: "edit-record" */ '@/components/pages/EditRecord'),
        meta: {
            requireAuth: true
        }
    },
    {
        path: '/404',
        name: '404',
        component: NotFound
    },
    {
        path: '*',
        redirect: '/404'
    }

]


if (sessionStorage.getItem("store")) {
    console.log(sessionStorage.getItem("store"))
    store.replaceState(Object.assign({}, store.state, JSON.parse(sessionStorage.getItem("store"))))
    if (store.state.token) {
        setAuth(store.state.token);
    }
}

const router = new VueRouter({
    base: process.env.BASE_URL,
    routes
})

router.beforeEach((to, from, next) => {
    if (to.meta.requireAuth) {
        // console.log(to.fullPath);
        if (store.state.login && ((new Date()).getTime() - store.state.loginTime) < store.state.second * 1000) {
            next()
        } else {
            next({
                path: '/login', query: {
                    redirect: to.fullPath
                }
            })
        }
    }
    else {
        next()
    }
})

export default router